package org.nobody.mallb2c.mallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.nobody.common.to.es.SkuEsModel;
import org.nobody.mallb2c.mallsearch.config.MallElasticSearchConfig;
import org.nobody.mallb2c.mallsearch.constant.EsConstant;
import org.nobody.mallb2c.mallsearch.service.ProductSaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-02-22:00
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
  @Autowired
  RestHighLevelClient restHighLevelClient;

  @Override
  public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
    //1、 给es中建立索引、映射关系(需要手动通过kibana等提前创建好)
    //2丶 给es中保存这些数据
    BulkRequest bulkRequest = new BulkRequest();
    for (SkuEsModel model : skuEsModels) {
      IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
      indexRequest.id(model.getSkuId().toString());
      String s = JSON.toJSONString(model);
      indexRequest.source(s, XContentType.JSON);
      bulkRequest.add(indexRequest);
    }
    BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);

    //todo 如果批量操作错误
    boolean b = bulk.hasFailures(); //true 表示有错误; false才表示没有错误
    //List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
    //  return item.getId();
    //}).collect(Collectors.toList());

    return b;
  }
}

